﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Wicresoft.UnifyShow.Business;
using Wicresoft.UnifyShow.Business.Models;
using Wicresoft.UnifyShow.BusinessImpl;
using Wicresoft.UnifyShow2.Portal.Models;
using Wicresoft.UnifyShow2.Portal.Service;
using System.IO;

namespace Wicresoft.UnifyShow2.Portal.Controllers
{
    [Authorize]
    public class DutyPlanController : BaseController
    {

        private IUser_X user;
        private IDutyPlan dutyplan;

        protected override void Dispose(bool disposing)
        {
            ((IDisposable)user).Dispose();
            ((IDisposable)dutyplan).Dispose();
        }
        [InjectionConstructor]
        public DutyPlanController(IUser_X _user, IDutyPlan _dutyplan)
        {
            this.user = _user;
            this.dutyplan = _dutyplan;
        }
        //
        // GET: /DutyPlan/


        public ActionResult Index()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            ViewBag.Msg = "";
            return View();
        }

        [HttpPost]
        public ActionResult Index(string temp)
        {
            string msg = "";
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");

            foreach (string upload in Request.Files)
            {
                if (!DocumentService.HasFile(Request.Files[upload])) continue;
                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"DutyPlanDoc\Files";
                string path = DocumentService.HasFolder(createPath);
                string fileOldName = Path.GetFileName(Request.Files[upload].FileName);
                string extension = Path.GetExtension(fileOldName);

                if (!extension.Contains("xls"))
                {
                    msg = "文件上传失败！请重新操作。";
                    break;

                }

                Stream fileStream = Request.Files[upload].InputStream;
                string fileNewName = DocumentService.RandomNumberToName() + extension;
                try
                {
                    Request.Files[upload].SaveAs(Path.Combine(path, fileNewName));
                    DocumentService.UpLoadRunProcess(fileNewName, CurrentUser.Company, CurrentUser.Name, out msg);
                }
                catch (Exception ex)
                {
                    SysLog.WriteSysLog(ex.ToString());
                    msg = "文件上传失败！请重新操作。";
                }

            }
            ViewBag.Msg = msg;
            return View();
        }

        public ActionResult UpLoad()
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            return View();
        }

        [HttpPost]
        public ActionResult UpLoadDutyPlan()
        {
            string msg = "";
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");

            foreach (string upload in Request.Files)
            {
                if (!DocumentService.HasFile(Request.Files[upload])) continue;
                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"DutyPlanDoc\Files";
                string path = DocumentService.HasFolder(createPath);
                string fileOldName = Path.GetFileName(Request.Files[upload].FileName);
                string extension = Path.GetExtension(fileOldName);

                if (!extension.Contains("xls"))
                {
                    break;
                    throw new Exception("请上传Excel格式文件！");
                }

                Stream fileStream = Request.Files[upload].InputStream;
                string fileNewName = DocumentService.RandomNumberToName() + extension;
                try
                {
                    Request.Files[upload].SaveAs(Path.Combine(path, fileNewName));
                    DocumentService.UpLoadRunProcess(fileNewName, CurrentUser.Company, CurrentUser.Name, out msg);
                    ViewBag.Msg = msg;
                }
                catch (Exception ex)
                {
                    SysLog.WriteSysLog(ex.ToString());
                    throw new Exception("文件上传失败！请重新操作。");
                }

            }
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 获取值班计划排版数据
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult GetPlanData(string start, string end)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;

            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            DateTime now = DateTime.Now;
            DateTime startdt = new DateTime(now.Year, now.Month, 1);
            DateTime enddt = startdt.AddMonths(1).AddDays(-1);
            if (start != null && end != null)
            {
                startdt = DateTime.ParseExact(start, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture);
                enddt = DateTime.ParseExact(end, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture);
            }

            IDutyPlan plan = new DutyPlan();
            var list = plan.GetDutyPlanByTime(startdt, enddt, site.ID);
            List<DutyPlanCalendarEventModel> dp = new List<DutyPlanCalendarEventModel>();
            foreach (var item in list)
            {
                dp.Add(new DutyPlanCalendarEventModel
                {
                    start = item.DutyDay.ToString("yyyy-MM-dd"),
                    end = item.DutyDay.ToString("yyyy-MM-dd"),
                    allDay = true,
                    title = item.WatchKeeper,
                    //Index = item.DutyDay.Month * 100 + item.DutyDay.Day,
                });

            }
            //var tempDate = startdt;
            //while (tempDate < enddt)
            //{
            //    if (!dp.Any(o => o.Index == tempDate.Month * 100 + tempDate.Day))
            //    {
            //        dp.Add(new DutyPlanCalendarEventModel
            //    {
            //        start = tempDate.ToString("yyyy-MM-dd HH:mm:ss"),
            //        end = tempDate.ToString("yyyy-MM-dd HH:mm:ss"),
            //        allDay = true,
            //        title = "未设置值班人",
            //        Index = tempDate.Month * 100 + tempDate.Day,
            //        editable = false
            //    }
            //            );
            //    }
            //    tempDate = tempDate.AddDays(1);
            //}


            return Json(dp);
        }

        /// <summary>
        /// 查看排版计划
        /// </summary>
        /// <returns></returns>
        public ActionResult SeeDutyPlan()
        {
            IPlanManagement _plan = new PlanManagement();

            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            var locationRange = _plan.GetSiteALLBranch();
            ViewBag.IsGlobalAdmin = ViewBag.IsConfigAdmin && site.Alias.Equals("省局");
            ViewData["Location"] = site;
            ViewData["LocationList"] = locationRange.OrderBy(x => x.LocationID).ToList();

            return View();
            //DateTime now = DateTime.Now;
            //DateTime startdt = new DateTime(now.Year, now.Month, 1);
            //DateTime enddt = startdt.AddMonths(1).AddDays(-1);

            //IDutyPlan plan = new DutyPlan();
            //var list = plan.GetDutyPlanByTime(startdt, enddt, site.ID);

            //return View(list);
        }

        [HttpPost]
        public JsonResult GetDutyPlanList(QueryString query, int page, int rows, string sort = "ID", string order = "Descending")
        {

            IDutyPlan dutyPlan = new DutyPlan();

            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;

            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            decimal total = 0;
            var list = dutyPlan.QueryDutyLog(query.startDate, query.endDate, query.locationID, out total, page, rows, sort, order);

            foreach (var item in list)
            {
                var dutyPlanInfo = dutyPlan.GetDutyPlanByID((int)item.PlanID);

                var location = user.GetSiteBranchBySiteID(item.SITEID);
                if (location != null)
                {
                    item.LocationName = location.Name;
                }

                if (dutyPlanInfo != null)
                {
                    item.WatchKeeper = dutyPlanInfo.WatchKeeper;
                    item.DutyPhone = dutyPlanInfo.DutyPhone;
                }
            }

            return Json(new { rows = list, total = total }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult SeeDutyPlanByTime(string start, string end)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;

            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            DateTime now = DateTime.Now;
            DateTime startdt = new DateTime(now.Year, now.Month, 1);
            DateTime enddt = startdt.AddMonths(1).AddDays(-1);

            if (start != null && end != null)
            {
                startdt = DateTime.ParseExact(start, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                enddt = DateTime.ParseExact(end, "yyyy/MM/dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
            }

            IDutyPlan plan = new DutyPlan();
            var list = plan.GetDutyPlanByTime(startdt, enddt, site.ID);

            return Json(list);
        }



        //
        // GET: /DutyPlan/Details/5

        public ActionResult Details(int id)
        {
            IDutyPlan plan = new DutyPlan();
            var model = plan.GetDutyPlanByID(id);
            return View(model);
        }

        public ActionResult Edit(string Status, int? ID)
        {
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            ViewData["canEdit"] = string.Equals(Status, "ADD", StringComparison.OrdinalIgnoreCase);

            IDutyPlan plan = new DutyPlan();
            var model = plan.GetTodayDutyInfo(site.ID);

            var log = new DutyLog();

            if (ID.HasValue)
            {
                log = plan.GetDutyLogByID(ID.Value);
            }
            else
            {
                log = plan.GetDutyLogDutyDay(model.DutyDay, site.ID);
            }

            ViewData["DutyLog"] = log;

            TempData["DutyPlan"] = model;
            TempData["DutyLog"] = log;

            return View(model);
        }

        public JsonResult AddDutyLog(string record)
        {
            var model = TempData["DutyPlan"] as DutyPlanModel;
            TempData["DutyPlan"] = model;

            var log = TempData["DutyLog"] as DutyLog;
            TempData["DutyLog"] = log;

            IDutyPlan _dutyPlan = new DutyPlan();

            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            if (model != null && log != null)
            {
                log.ModifyBy = CurrentUser.DisplayName;
                log.ModifyTime = DateTime.Now;
                log.DailyRecord = record;

                var result = _dutyPlan.InsertDutyLog(log);

                return Json(result ? "OK" : "Error", JsonRequestBehavior.AllowGet);
            }

            return Json("Error", JsonRequestBehavior.AllowGet);
        }

        public ActionResult List()
        {
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(x => x.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");

            IDutyPlan plan = new DutyPlan();
            var model = plan.GetTodayDutyInfo(site.ID);
            if (model.WatchKeeper == null)
            {
                model.WatchKeeper = "未安排!";
                model.DutyDay = DateTime.Now;
            }
            return PartialView(model);
        }

        //
        // GET: /DutyPlan/Create

        public ActionResult Create(string start, string end, bool allDay)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;
            var CurrentUser = user.GetUser_XByName(User.Identity.Name);
            if (CurrentUser == null)
                throw new Exception("USER_X is null.");
            var site = user.GetSiteBranchByID(CurrentUser.ID).FirstOrDefault(s => s.Name == CurrentUser.Company);
            if (site == null)
                throw new Exception("UserSite is null.");


            DateTime startdt = DateTime.ParseExact(start, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture);
            DateTime enddt = DateTime.ParseExact(end, "yyyy/MM/dd", System.Globalization.CultureInfo.InvariantCulture);
            DutyPlanCalendarModel model = new DutyPlanCalendarModel();
            var dutyModel = dutyplan.GetDutyPlanByDutyDay(startdt, site.ID);

            model.StartDate = startdt.ToString("yyyy/MM/dd");
            model.EndDate = enddt.ToString("yyyy/MM/dd");
            if (dutyModel != null)
            {
                model.WatchKeeper = dutyModel.WatchKeeper;
                model.DutyPhone = dutyModel.DutyPhone;
            }
            return PartialView(model);
        }

        //
        // POST: /DutyPlan/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            base.SetRoles(user);
            ViewBag.IsConfigAdmin = IsConfigAdmin;

            var user_x = user.GetUser_XByName(User.Identity.Name);
            if (user_x == null)
                throw new Exception("USER_X is null.");
            var siteid = user.GetSiteBranchByID(user_x.ID).FirstOrDefault(s => s.Name == user_x.Company).ID;

            DateTime start = Convert.ToDateTime(Request.Form["StartDate"]);
            DateTime end = Convert.ToDateTime(Request.Form["EndDate"]);
            string watchKeeper = Request.Form["WatchKeeper"].ToString();
            string dutyPhone = Request.Form["DutyPhone"].ToString();

            IDutyPlan plan = new DutyPlan();
            List<DutyPlanModel> insertlist = new List<DutyPlanModel>();
            List<DutyPlanModel> updatelist = new List<DutyPlanModel>();

            do
            {
                DutyPlanModel newplan = new DutyPlanModel()
                {
                    DutyDay = start,
                    CreateTime = DateTime.Now,
                    WatchKeeper = watchKeeper,
                    ModifyTime = DateTime.Now,
                    Submitter = user_x.Name,
                    SITEID = siteid,
                    ModifyBy = user_x.Name,
                    DutyPhone = dutyPhone
                };
                if (plan.IsExist(start, siteid))
                    updatelist.Add(newplan);
                else
                    insertlist.Add(newplan);

                start = start.AddDays(1);
            }
            while (start <= end);

            try
            {
                // TODO: Add insert logic here or Update logic here
                int ret1 = 0, ret2 = 0;
                if (insertlist.Count > 0)
                    ret1 = plan.AddList(insertlist);
                if (updatelist.Count > 0)
                    ret2 = plan.UpdateList(updatelist);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /DutyPlan/Delete/5

        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /DutyPlan/Delete/5

        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            try
            {
                base.SetRoles(user);
                ViewBag.IsConfigAdmin = IsConfigAdmin;

                var user_x = user.GetUser_XByName(User.Identity.Name);
                if (user_x == null)
                    throw new Exception("USER_X is null.");
                var siteid = user.GetSiteBranchByID(user_x.ID).FirstOrDefault(x => x.Name == user_x.Company).ID;

                IDutyPlan plan = new DutyPlan();
                DateTime start = Convert.ToDateTime(Request.Form["StartDate"]);
                DateTime end = Convert.ToDateTime(Request.Form["EndDate"]);

                var deleteList = new List<DutyPlanModel>();

                do
                {
                    DutyPlanModel newplan = new DutyPlanModel()
                    {
                        DutyDay = start,
                        CreateTime = DateTime.Now,
                        ModifyTime = DateTime.Now,
                        Submitter = user_x.Name,
                        SITEID = siteid,
                        ModifyBy = user_x.Name,
                    };

                    if (plan.IsExist(start, siteid))
                    {
                        deleteList.Add(newplan);
                    }

                    start = start.AddDays(1);
                }

                while (start <= end);

                if (deleteList.Count > 0)
                {
                    plan.DeleteList(deleteList);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
